<template>
  <common-layout>
    <div class="top">
      <div class="header">
        <img alt="logo" class="logo" src="@/assets/img/logo.png" />
        <span class="title">{{ systemName }} 后台管理系统</span>
      </div>
      <div class="desc"></div>
    </div>
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-alert
          type="error"
          :closable="true"
          v-show="error"
          :message="error"
          showIcon
          style="margin-bottom: 24px;" />
        <a-form-item>
          <a-input
            autocomplete="autocomplete"
            size="large"
            placeholder="请输入用户名"
            v-decorator="['name', {rules: [{ required: true, message: '请输入用户名', whitespace: true}]}]"
          >
            <a-icon slot="prefix" type="user" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            size="large"
            placeholder="请输入密码"
            autocomplete="autocomplete"
            type="password"
            v-decorator="['password', {rules: [{ required: true, message: '请输入密码', whitespace: true}]}]"
          >
            <a-icon slot="prefix" type="lock" />
          </a-input>
        </a-form-item>

        <a-row :gutter="0" v-if="needAuthCode">
          <a-col :span="16">
            <a-form-item>
              <a-input
                v-decorator="['inputCode', {rules: [{ required: true, message: '请输入验证码', whitespace: true}]}]"
                size="large"
                type="text"
                @change="inputCodeChange"
                placeholder="请输入验证码">
                <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" style="text-align: right">
            <img v-if="requestCodeSuccess" style="margin-top: 2px;width: 105px;height: 35px;" :src="randCodeImage" @click="handleChangeCheckCode"/>
            <img v-else style="margin-top: 2px;" src="../../assets/checkcode.png" @click="handleChangeCheckCode"/>
          </a-col>
        </a-row>
        <a-form-item>
          <a-button :loading="logging" style="width: 100%;margin-top: 24px" size="large" htmlType="submit" type="primary">登录</a-button>
        </a-form-item>
      </a-form>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout'
import { mapActions, mapMutations } from 'vuex'
import { apiGetRandomImage } from '@/api/system'
import Vue from 'vue'
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
import { timeFix } from '@/utils/util'

export default {
  name: 'Login',
  components: { CommonLayout },
  data () {
    return {
      currdatetime: '',
      requestCodeSuccess: false,
      inputCodeContent: '',
      logging: false,
      error: '',
      form: this.$form.createForm(this),
      needAuthCode: false
    }
  },
  computed: {
    systemName () {
      return this.$store.state.setting.systemName
    }
  },
  created () {
    this.currdatetime = new Date().getTime()
    Vue.ls.remove(ACCESS_TOKEN)
    this.handleChangeCheckCode()
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    handleChangeCheckCode () {
      this.requestCodeSuccess = false
      this.currdatetime = new Date().getTime()
      apiGetRandomImage(this.currdatetime).then(res => {
        console.log(res)
        this.randCodeImage = window.URL.createObjectURL(res)
        this.requestCodeSuccess = true
      }).catch(() => {
        this.requestCodeSuccess = false
      })
    },
    inputCodeChange (e) {
      this.inputCodeContent = e.target.value
    },
    onSubmit (e) {
      const loginParams = {}
      const that = this
      e.preventDefault()
      this.form.validateFields((err) => {
        if (!err) {
          this.logging = true
          loginParams.loginName = this.form.getFieldValue('name')
          loginParams.password = this.form.getFieldValue('password')
          loginParams.imgCaptcha = that.inputCodeContent
          // loginParams.checkKey = that.currdatetime
          that.Login(loginParams).then((res) => {
            if (!res.data.isLogin) {
              that.needAuthCode = res.data.needAuthCode
              throw new Error(res.data.errorMsg || '登录异常！')
            } else {
              Vue.ls.set(ACCESS_TOKEN, true)
              const user = {
                name: 'admin',
                avatar: 'AVATAR',
                address: 'CITY',
                position: 'POSITION'
              }
              this.setUser(user)
              that.loginSuccess()
            }
          }).catch((err) => {
            that.requestFailed(err)
          }).finally(() => {
            that.logging = false
          })
        }
      })
    },
    loginSuccess () {
      this.$router.push(INDEX_MAIN_PAGE_PATH)
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    requestFailed (err) {
      console.log(err.message)
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .common-layout{
    .top {
      text-align: center;
      .header {
        height: 44px;
        line-height: 44px;
        a {
          text-decoration: none;
        }
        .logo {
          height: 44px;
          vertical-align: top;
          margin-right: 16px;
        }
        .title {
          font-size: 33px;
          color: @title-color;
          font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
          font-weight: 600;
          position: relative;
          top: 2px;
        }
      }
      .desc {
        font-size: 14px;
        color: @text-color-second;
        margin-top: 12px;
        margin-bottom: 40px;
      }
    }
    .login{
      width: 368px;
      margin: 0 auto;
      @media screen and (max-width: 576px) {
        width: 95%;
      }
      @media screen and (max-width: 320px) {
        .captcha-button{
          font-size: 14px;
        }
      }
      .icon {
        font-size: 24px;
        color: @text-color-second;
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: @primary-color;
        }
      }
    }
  }
</style>
